package cn.edu.nju.ws.sview.group;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import cn.edu.nju.ws.sview.cache.MessageCache;
import cn.edu.nju.ws.sview.database.DBConnectionFactory;
import cn.edu.nju.ws.sview.views.Group;
import cn.edu.nju.ws.sview.views.Message;
import cn.edu.nju.ws.sview.views.User;

public class MessageServlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml;charset=utf-8");
		String result=null;
		String json = request.getParameter("msg");
		System.out.println("msg..."+json);
		if(json != null){
			URLDecoder coder = new URLDecoder();
			String data = coder.decode(json, "utf8");
			JSONObject regtJSON = (JSONObject) JSONValue.parse(data);
			String action = (String) regtJSON.get("action");
			if(action.contentEquals("getReceiveMessage")){
				String uname = (String) regtJSON.get("value");
				int uid = User.getUserIdByName(uname);//User.getUserIdByName((String)request.getSession().getAttribute("user"));
				Document doc = Message.getReceiveMessageByUserId(uid);
//				System.out.println("doc:"+doc.asXML());
				response.getWriter().print(doc.asXML());
			}else if(action.contentEquals("removeMessage")){
				String value = (String) regtJSON.get("value");
				String uname = (String) regtJSON.get("value");
				int uid = User.getUserIdByName(uname);
				if(value.length()>0){
					value = value.substring(0,value.length()-1);
					
					try {
						Connection conn = DBConnectionFactory.getConnection();
//						System.out.println("value:"+value);
						PreparedStatement pstmt = conn.prepareStatement("delete from msg where id in ("+value+")");
						pstmt.executeUpdate();
						MessageCache.getInstance().updateMessages(uid);
						pstmt.close();
						conn.close();
						result="success";
						response.getWriter().print(result);
					} catch (SQLException e) {
						e.printStackTrace();
						try {
							MessageCache.getInstance().updateMessages(uid);
						} catch (Throwable e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					} catch (Throwable e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}//end of if_value
				response.getWriter().print(result);
			}else if(action.contentEquals("accept")){
				String uname = (String) regtJSON.get("uname");
				String gname = (String) regtJSON.get("gname");
				String mid = (String) regtJSON.get("mid");
				int gid = Group.getGroupIdByName(gname);
				ArrayList<String> users = new ArrayList<String>();
				users.add(uname);						
				Group.addMember(gid, users);
				if(mid != null && updateMsgContent(Integer.valueOf(mid), User.getUserIdByName(uname),1)){
					result = "success";
				}else{
					result = "failed";
				}
				response.getWriter().print(result);
			}else if(action.contentEquals("acceptApply")){
				String uname = (String) regtJSON.get("uname");
				String adminname = (String) regtJSON.get("adminname");
				String gname = (String) regtJSON.get("gname");
				String mid = (String) regtJSON.get("mid");
				int gid = Group.getGroupIdByName(gname);
				ArrayList<String> users = new ArrayList<String>();
				users.add(uname);						
				Group.addMember(gid, users);
				if(mid != null && updateMsgContent(Integer.valueOf(mid), User.getUserIdByName(adminname),2)){
					result = "success";
				}else{
					result = "failed";
				}
				response.getWriter().print(result);
			}else if(action.contentEquals("reject")){
				String uname = (String) regtJSON.get("uname");
//				String gname = (String) regtJSON.get("gname");
				String mid = (String) regtJSON.get("mid");
				if(mid != null && updateMsgContent(Integer.valueOf(mid), User.getUserIdByName(uname),1)){
					result = "success";
				}else{
					result = "failed";
				}
				response.getWriter().print(result);
			}else if(action.contentEquals("rejectApply")){
				String uname = (String) regtJSON.get("uname");
//				String gname = (String) regtJSON.get("gname");
				String mid = (String) regtJSON.get("mid");
				System.out.println(mid+"---"+uname);
				if(mid != null && updateMsgContent(Integer.valueOf(mid), User.getUserIdByName(uname),2)){
					result = "success";
				}else{
					result = "failed";
				}
				response.getWriter().print(result);
			}
		}//end of if_json
	}
	private boolean updateMsgContent(int mid, int uid,int type){
		try {
			System.out.println(mid+"---"+uid);
			Connection conn = DBConnectionFactory.getConnection();
			PreparedStatement pstmt = conn.prepareStatement("select content from msg where id=?");
			PreparedStatement update = conn.prepareStatement("update msg set content=? where id=?");
			pstmt.setInt(1, mid);
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()){
				String content = rs.getString(1);
				if(type==1){
					content=content.replace("<a class='accept' href='javascript:void(0)'>accept</a>", "accept");
					content=content.replace("<a class='reject' href='javascript:void(0)'>reject</a>", "reject");
				}else{
					content=content.replace("<a class='acceptApply' href='javascript:void(0)'>accept</a>", "accept");
					content=content.replace("<a class='rejectApply' href='javascript:void(0)'>reject</a>", "reject");
				}
				update.setString(1, content);
				update.setInt(2, mid);
				update.executeUpdate();
			}
			rs.close();
			update.close();
			pstmt.close();
			conn.close();
			MessageCache.getInstance().updateMessages(uid);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
}
